# coding: utf-8
import os,time
import pytesseract
import numpy as np
import cv2
import xlwt

# 设置tesseract可执行程序及中文字库的路径
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract'
tessdata_dir_config = r'--tessdata-dir "C:\Program Files\Tesseract-OCR\tessdata"'
filepath='D:\program\pythonDeam\myocr\\testphotos\\'
name=os.listdir(filepath)
f = xlwt.Workbook()
sheet1 = f.add_sheet(u'sheet111', cell_overwrite_ok=True)  # 创建sheet
# 将数据写入第 i 行，第 j 列
i=1
time0=time.time()
for item in name:
    #img = cv2.imread("D:\\program\\pythonDeam\\myocr\\220101B.png",cv2.IMREAD_UNCHANGED)
    phfile=filepath + item
    img=cv2.imread(phfile,cv2.IMREAD_UNCHANGED)  #读取png
   

# 设定图片区域，坐标从getxy.py获取
    img_roi = img[380:420, 380:480]
    #图片腐蚀
    kernel = np.ones((5,5),np.uint8)  
    erosion = cv2.erode(img_roi,kernel,iterations = 100)
    # cv2.namedWindow("roi")
    # cv2.imshow("roi", img_roi)
    # cv2.waitKey(0)
    
    text = pytesseract.image_to_string(img_roi, config=tessdata_dir_config).strip()
#text=pytesseract.image_to_string(img)
    print(phfile,text)
    sheet1.write(i,1,phfile)
    sheet1.write(i,2,text)
    i+=1
time1=time.time()
print(time1-time0)
# 由于图片上字符间距的原因，识别出的文本中可能会包含空格，使用下列语句去除空格
# for r in text.splitlines():
#     print(r.replace(" ", ""))




f.save(r"D:\program\pythonDeam\myocr\result.xls")  # 保存文件
print("完成")
